package com.k2.exstrasensorytypredictor;

import java.io.IOException;
import java.util.Random;

import com.k2.exstrasensorytypredictor.containers.GfxResourceContainer;
import com.k2.exstrasensorytypredictor.containers.UserPoints;
import com.k2.exstrasensorytypredictor.controls.MButton;
import com.k2.exstrasensorytypredictor.dialogs.IOnDialogButtonPressed;
import com.k2.exstrasensorytypredictor.dialogs.MDialog;
import com.k2.exstrasensorytypredictor.interfaces.IConstants;
import com.k2.exstrasensorytypredictor.interfaces.ITouchHandler;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.R.anim;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PictScreen extends Activity implements ITouchHandler, IConstants, IOnDialogButtonPressed {
	
	private RelativeLayout layout;
	private MButton[] buttons;
	private TextView text;
	private RelativeLayout.LayoutParams params;
	private float koeffX;
	private float koeffY;
	private Random rnd;
	private int pcResult;
	private int userResult;
	private boolean isWinner;
	private boolean isNeedToDrawTitle;
	private Matrix m;
	private AssetFileDescriptor afd;
	private MediaPlayer player;
	private int points = 2;
	private int action;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.initUI();
        this.initLaout();
	}
	
	private void initUI() {
		rnd = new Random(System.currentTimeMillis());
		while ((pcResult = rnd.nextInt(10)) == 10){}
		this.koeffX = (float)getWindowManager().getDefaultDisplay().getWidth() / SCREEN_RES_X;
    	this.koeffY = (float)getWindowManager().getDefaultDisplay().getHeight() / SCREEN_RES_Y;
		this.buttons = new MButton[PICT_SCR_BTN_COORDS.length];
		for (int i = 0; i < this.buttons.length; i++) {
			this.buttons[i] = new MButton(this, new Bitmap[]{GfxResourceContainer.getInstance(this).getpScrBitmaps()[i],
					GfxResourceContainer.getInstance(this).getpScrBitmaps()[i]}, i, true);
		}
	}
	
	private void initLaout() {
		isNeedToDrawTitle = true;
		m = new Matrix();
		m.setScale(koeffX, koeffY);
		m.postTranslate(PICT_SCR_TITLE_COORDS[0] * koeffX, PICT_SCR_TITLE_COORDS[1] * koeffY);
		this.layout = new RelativeLayout(this){
			@Override
			protected void onDraw(Canvas canvas) {
				if (isNeedToDrawTitle) {
					canvas.drawBitmap(GfxResourceContainer.getInstance(PictScreen.this).getpScrTitle(), m, null);
				}
			}
		};
		this.params = new RelativeLayout.LayoutParams((int)(SCREEN_RES_X * this.koeffX), (int)(SCREEN_RES_Y * this.koeffY));
		layout.setBackgroundDrawable(GfxResourceContainer.getInstance(this).getMainBg());
		setContentView(this.layout, this.params);
		for (int i = 0; i < this.buttons.length; i++) {
			this.params = new RelativeLayout.LayoutParams((int)this.buttons[i].getBtnWidth(), (int)this.buttons[i].getBtnHeight());
			params.leftMargin = (int)(PICT_SCR_BTN_COORDS[i][0] * koeffX);
			params.topMargin = (int)(PICT_SCR_BTN_COORDS[i][1] * koeffY);
            layout.addView(buttons[i], params);
		}
	}
	
	private void verifyResult(int res){
		if (res == pcResult){
			this.isWinner = true;
			UserPoints.getInstance().getUsers()[UserPoints.getInstance().getActiveUserIndex()].scores += points;
			try {
				this.afd = getAssets().openFd(SOUNDS[0]);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			this.isWinner = false;
			try {
				this.afd = getAssets().openFd(SOUNDS[1]);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		m = new Matrix();
		m.setScale(koeffX, koeffY);
		m.postTranslate((float)getWindowManager().getDefaultDisplay().getWidth()/2 - (float)GfxResourceContainer.getInstance(PictScreen.this).getpScrBitmaps()[pcResult + 10].getWidth()*koeffX/2,
				(float)getWindowManager().getDefaultDisplay().getHeight()/2 - (float)GfxResourceContainer.getInstance(PictScreen.this).getpScrBitmaps()[pcResult + 10].getHeight()*koeffY/2);
		View resultView = new View(this){
			@Override
			protected void onDraw(Canvas canvas) {
				canvas.drawBitmap(GfxResourceContainer.getInstance(PictScreen.this).getpScrBitmaps()[pcResult + 10], m, null);
			}
		};
		this.layout.removeAllViews();
		isNeedToDrawTitle = false;
		layout.invalidate();
		this.layout.addView(resultView);
		this.player = new MediaPlayer();
		try {
			this.player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			this.player.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.player.start();
		if (UserPoints.getInstance().getUserAmount() == 1){
			this.action = EXIT;
			int a = (new MDialog(this, this, DIALOG_TEXTS[0][0] + String.valueOf(UserPoints.getInstance().getUsers()[0].scores) + "\n" + DIALOG_TEXTS[0][4],
					new String[]{DIALOG_TEXTS[0][9], DIALOG_TEXTS[0][10]}, false, MDialog.DIALOG_YES_NO)).showDialog();
		} else if (UserPoints.getInstance().getUserAmount() == 2){
			if (UserPoints.getInstance().getActiveUserIndex() == 0){
				this.action = SHOW_RESULTS;
				int a = (new MDialog(this, this, DIALOG_TEXTS[0][0] + String.valueOf(UserPoints.getInstance().getUsers()[0].scores),
						new String[]{DIALOG_TEXTS[0][11]}, false, MDialog.DIALOG_OK)).showDialog();
				UserPoints.getInstance().switchActiveUser();
				
			} else if (UserPoints.getInstance().getActiveUserIndex() == 1){
				this.action = EXIT;
				int a = (new MDialog(this, this, DIALOG_TEXTS[0][0] + 
						String.valueOf(UserPoints.getInstance().getUsers()[UserPoints.getInstance().getActiveUserIndex()].scores) + "\n" + DIALOG_TEXTS[0][4],
						new String[]{DIALOG_TEXTS[0][9], DIALOG_TEXTS[0][10]}, false, MDialog.DIALOG_YES_NO)).showDialog();
				UserPoints.getInstance().switchActiveUser();
			}
		}
	}
	
	@Override
	public boolean onAreaTouched(View view, MotionEvent event) {
		this.userResult = ((MButton)view).getId();
		this.verifyResult(userResult);
		return false;
	}
	
	@Override
	public void overridePendingTransition(int enterAnim, int exitAnim) {
		// TODO Auto-generated method stub
		super.overridePendingTransition(anim.slide_in_left, anim.slide_out_right);
	}

	@Override
	public void OnDialogButtonPressed(int message) {
		switch (action) {
		case EXIT:
		if (message == MDialog.ANSWER_YES){
			finish();
			startActivity(new Intent(this, PictScreen.class));
		} else if (message == MDialog.ANSWER_NO){
			finish();
			//startActivity(new Intent(this, MainScreen.class));
		}
		break;
		case SHOW_RESULTS:
			finish();
			startActivity(new Intent(this, PictScreen.class));
			break;

		default:
			break;
		}
	}
}
